//
//  MLHomeViewModel.swift
//  MLWeiBo
//
//  Created by wenxing on 2017/1/9.
//  Copyright © 2017年 Se7venX. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage

class MLHomeViewModel: NSObject {
    
    // status
    var viewModelArray = [MLStatusViewModel]()
    
    // cell - statusVM - status
    // vc - [statusVM]
    
    func loadHomeData(isUp:Bool, finished:@escaping (Bool,Int)->()){
        
        
        var since_id:Int64 = 0
        var max_id:Int64 = 0
        
        if isUp {  //上拉
            
            max_id = viewModelArray.last?.status?.id ?? 0
            
            if max_id > 0 {
                
                max_id -= 1
            }
            
            
        }else{
            
            since_id = viewModelArray.first?.status?.id ?? 0
            
        }
        
        let urlString = urlString_homeStatus + "?access_token=" + (MLUserAccountViewModel.shared.userAccount?.access_token)! + "&since_id=" + "\(since_id)"+"&max_id=" + "\(max_id)"
        
//        print("urlString:::",urlString)
        
        MLNetworkTool.shared.ml_requestData(method: .GET, url: urlString, parameters: nil) { (response, error) in
            
            if error != nil {
                
                print(error!)
                finished(false,0)
                return
            }
            
            //1.先确定有没有值
            guard let objc = response as? [String:Any] else{
                
                return
            }
            
            //2.再拿出字典数组
            let array = objc["statuses"] as! [[String:Any]]
            
            //3.临时数组
            var tempArray = [MLStatusViewModel]()
            
            //字典转模型
            for obj in array {
                
                let vm = MLStatusViewModel()
                let s = MLStatus()
                
                s.yy_modelSet(with: obj)
                
                vm.status = s
                
                tempArray.append(vm)
            }
            
            if isUp {
            
                self.viewModelArray = self.viewModelArray + tempArray
                
            }else{
            
                self.viewModelArray = tempArray + self.viewModelArray
            }
            
            self.cacheStatusSingleImage(dataArray: self.viewModelArray, finished: finished)
//             print(NSHomeDirectory())
        }
        
    }
    
    /// 缓存单张图片
    private func cacheStatusSingleImage(dataArray:[MLStatusViewModel],finished:@escaping(Bool,Int)->()) {

        
        if dataArray.count == 0 {
            
            finished(false,0)
            
            return
        }
        
        let group = DispatchGroup()
        
        
        for viewModel in dataArray {
            
           // print("^^^数组个数:::",viewModel.all_pic_urls?.count)
         
            if  (viewModel.all_pic_urls?.count ?? 0) == 1{

                let url = viewModel.all_pic_urls?.last?.wap360 ?? ""
                
//                print("url:::",url)
                
                group.enter()
                
                SDWebImageManager.shared().downloadImage(with: URL(string: url), options: [], progress: nil, completed: { (_, _, _, _, _) in

                    group.leave()
                    
                })
            }
        }
        
        group.notify(queue: DispatchQueue.main) {
            
            finished(true,dataArray.count)
        }
    }
}
